package leetcode;

import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Ghost
 * Date: 14-5-29
 * Time: 下午6:41
 * To change this template use File | Settings | File Templates.
 */
public class Solution2 {
    public String getFormalNum(ArrayList<String> list, int index){
        for(int i=1;i<=index;i++){
            if(!list.get(index-i).equals("|")){
                String num = list.get(index-i);
                list.set(index-i,"|");
                return num;
            }
        }
        return null;
    }
    public int evalRPN(String[] tokens) {
        ArrayList<String> list = new ArrayList<String>();
        for(int i=0;i<tokens.length;i++){
            list.add(tokens[i]);
        }
        int size = list.size();
        for(int i=0;i<size;i++){
            String num = list.get(i);
            if(num.equals("+")||num.equals("-")||num.equals("*")||num.equals("/")){
                int b = Integer.parseInt(getFormalNum(list,i));
                int a = Integer.parseInt(getFormalNum(list,i));
                if(num.equals("+")){
                    list.set(i,""+(a+b));
                }
                else if(num.equals("-"))
                {
                    list.set(i,""+(a-b));
                }
                else if(num.equals("*")){
                    list.set(i,""+(a*b));
                }
                else if(num.equals("/")){
                    list.set(i,""+(a/b));
                }
            }
        }
        return Integer.parseInt(list.get(size-1));
    }

}
